<?php


namespace app\api\controller;


use app\BaseController;
use app\wechat\controller\AuthBase;
use Composer\Autoload\ClassLoader;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\console\command\VendorPublish;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;

class Record extends AuthBase
{
//    protected $noLogin = ['getCity','phone_code'];
    /**
     * @return void
     * 记录烟费
     */
    public function add_cost(){
        $data=input('post.');
        try {
            validate(\app\common\validate\Record::class)
                ->scene("add_cost")
                ->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->show(0, $e->getError());
        }
        $data['buy_date']=strtotime($data['buy_date']);
        $data['create_time']=time();
        $data['update_time']=time();
        $data['user_id']=$this->userId;
//        $user_smoke=Db::name('user_smoke')
//            ->where('user_id',$this->userId)
//            ->where('id',$data['smoke_id'])
//            ->find();
//        if($user_smoke){
//            $data['smoke_id']=$user_smoke['smoke_id'];
//        }
        Db::startTrans();
        try {
            Db::name('smoke_cost_record')
                ->insert($data);
            Db::name('user_smoke')
                ->where('user_id',$this->userId)
                ->update(['type'=>2]);
            //记录到我的香烟
            $res=Db::name('user_smoke')
                ->where(['user_id'=>$this->userId,'smoke_id'=>$data['smoke_id']])
                ->inc('price',$data['price'])
                ->inc('num',$data['num'])
                ->update(['type'=>1]);
            if (!$res){
                //如果不存在则新增
                $smoke['smoke_id']=$data['smoke_id'];
                $smoke['num']=1;
                $smoke['type']=1;
                $smoke['user_id']=$this->userId;
                $smoke['price']=$data['price'];
                $smoke['create_time']=time();
                $smoke['update_time']=time();
                Db::name('user_smoke')->insert($smoke);
            }
            //记录热度
            Db::name('smoke')
                ->where('id',$data['smoke_id'])
                ->inc('hot',$data['num']*20)
                ->update();
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    /**
     * 删除烟费
     */
    public function del_cost(){
        $id=input('post.id');
        $smoke=Db::name('smoke_cost_record')
            ->where('id',$id)
            ->find();
        Db::startTrans();
        try {
            Db::name('smoke_cost_record')->where('id',$id)->delete();
            Db::name('user_smoke')
                ->where(['user_id'=>$this->userId,'smoke_id'=>$smoke['smoke_id']])
                ->dec('price',$smoke['price'])
                ->dec('num',$smoke['num'])
                ->update();
            Db::commit();
            return show(1, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    /**
     * 快速记
     */
    public function add_smoke(){
        $data=input('post.');
        $smoke=Db::name('smoke')
            ->where('id',$data['smoke_id'])
            ->find();
        Db::startTrans();
        try {
            //写入到记录表
            $result['smoke_date']=time();
            $result['num']=1;
            $result['smoke_arr']=json_encode([['smoke_id'=>$data['smoke_id'],'num'=>1]]);
            $result['tar']=$smoke['tar']*0.2;
            $result['nicotine']=$smoke['nicotine']*0.3;
            $result['co']=$smoke['co']*0.6;
            $result['user_id']=$this->userId;
            $result['create_time']=time();
            $result['update_time']=time();
            Db::name('smoke_record')->insert($result);
            //记录热度
            Db::name('smoke')
                ->where(['id'=>$data['smoke_id']])
                ->inc('hot',1)
                ->update();
            //记录到我的香烟列表
            $user_smoke=Db::name('user_smoke')
                ->where('user_id',$this->userId)
                ->count();
            if (!$user_smoke&&$data['smoke_id']>0){
                Db::name('user_smoke')
                    ->insert(['user_id'=>$this->userId,
                        'smoke_id'=>$data['smoke_id'],
                        'type'=>1,
                        'create_time'=>time(),
                        'update_time'=>time(),
                        ]);
            }
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    /**
     * 详细记录抽烟
     */
    public function add_smokes(){
        $data=input('post.');
        $smokes=$data['smokes'];
        $tar=0;
        $nicotine=0;
        $co=0;
        $num=0;
        $ids=array_column($smokes,'smoke_id');
        foreach ($smokes as $k=>$v){
            $smoke=Db::name('smoke')
                ->where('id',$v['smoke_id'])
                ->find();
            $tar+=$smoke['tar']*$v['num']*0.2;
            $nicotine+=$smoke['nicotine']*$v['num']*0.3;
            $co+=$smoke['co']*$v['num']*0.6;
            $num+=$v['num'];
        }
        Db::startTrans();
        try {
            //写入到记录表
            $result['smoke_date']=strtotime($data['smoke_date']);
            $result['num']=$num;
            $result['smoke_arr']=json_encode($smokes);
            $result['tar']=$tar;
            $result['nicotine']=$nicotine;
            $result['co']=$co;
            $result['user_id']=$this->userId;
            $result['create_time']=time();
            $result['update_time']=time();
            Db::name('smoke_record')->insert($result);
            //记录热度
            Db::name('smoke')
                ->where(['id'=>$ids])
                ->inc('hot',$num)
                ->update();
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    /**
     * 删除抽烟
     */
    public function del_smoke(){
        $id=input('post.id');
        Db::startTrans();
        try {
            Db::name('smoke_record')->where(['id'=>$id,'user_id'=>$this->userId])->delete();
            Db::commit();
            return show(1, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    /**
     * 计算摄入量
     */
    public function calculate_adi(){
        $smokes=input('post.smokes');
        $tar=0;
        $nicotine=0;
        $co=0;
        foreach ($smokes as $k=>$v){
            $smoke=Db::name('smoke')
                ->where('id',$v['smoke_id'])
                ->find();
            $tar+=$smoke['tar']*$v['num']*0.2;
            $nicotine+=$smoke['nicotine']*$v['num']*0.3;
            $co+=$smoke['co']*$v['num']*0.6;
        }
        $result['tar']=$tar;
        $result['nicotine']=$nicotine;
        $result['co']=$co;
        return $this->show(1,'',$result);
    }
    /**
     * 返回默认香烟
     */
    public function default_smoke(){
        $model=Db::name('user_smoke')
            ->alias('u')
            ->leftJoin('smoke s','s.id=u.smoke_id')
            ->where(['u.user_id'=>$this->userId,'u.type'=>1])
            ->field('u.*,s.name,s.tar,s.nicotine,s.co,s.price')
            ->find();
        return $this->show(1,'',$model);
    }
}